package tests;

import utils.Utils;
import mysql.Connection;
import mysql.Schema;

import java.util.Scanner;

/**
 * Created by nuno-rafael-figueiredo on 02-07-2014.
 */
public class Console {
    public static final Scanner SCANNER = new Scanner(System.in);

    public static Connection getDefaultConnection() {
        Connection connection = Utils.preferred(Connection.class, "default", null, Connection.class);

        if (connection == null)
            return askConnection();

        return confirm("Connection", connection) ? connection : askConnection();
    }

    private static Connection askConnection() {
        String hostname = ask("Hostname", "localhost");
        int port = ask("Port", Connection.DEFAULT_PORT);
        String user = ask("User", "root");
        String password = ask("Password", "root");
        String schema = ask("Schema", "");

        return new Connection(hostname, port, user, password, schema);
    }

    private static String ask(String field, String defaultValue) {
        if (defaultValue.length() > 0 && confirm(field, defaultValue))
            return defaultValue;

        System.out.print(field + ": ");
        return SCANNER.next();
    }

    private static int ask(String field, int defaultValue) {
        if (confirm(field, defaultValue))
            return defaultValue;

        System.out.print(field + ": ");
        return SCANNER.nextInt();
    }

    private static boolean confirm(String field, Object defaultValue) {
        String s;
        do{
            System.out.println(field + ": use '" + defaultValue + "' (s/n)?");
            s = SCANNER.next().toLowerCase();
        }while(s.length() != 1 && !"sn".contains(s));

        return s.equals("s");
    }

    public static Schema getDefaultSchema() {
        return getDefaultConnection().extract();
    }
}
